package com.three.vip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.three.core.entity.*;
import com.three.core.vo.R;
import com.three.vip.feign.AdminUserFeign;
import com.three.vip.mapper.*;
import com.three.vip.service.FrontUserService;
import com.three.vip.vo.AddCarVo;
import com.three.vip.vo.CustomerSearchFormVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ：JinShiYan
 * @date ：Created in 2025/3/12 17:22
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class FrontUserServiceImpl implements FrontUserService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FrontUserMapper frontUserMapper;

    @Autowired
    private UserBalanceLogMapper userBalanceLogMapper;

    @Autowired
    private UserIntegralLogMapper userIntegralLogMapper;

    @Autowired
    private AdminUserFeign adminUserFeign;

    @Autowired
    private FrontUserStoreMapper frontUserStoreMapper;

    @Autowired
    private UserBalanceMapper userBalanceMapper;

    @Autowired
    private UserIntegralMapper userIntegralMapper;

    @Override
    public R<IPage<FrontUser>> selectByCondition(CustomerSearchFormVo customerSearchFormVo) {
        //获取Token
        String token = request.getHeader("token");
        // 获取用户名
        Object user = redisTemplate.opsForHash().get("user::login::" + token, "name");
        R<User> byName = adminUserFeign.getByName((String) user);
        Integer userId = byName.getData().getUserId();
        Page<FrontUser> page = new Page<>(customerSearchFormVo.getCurrentPage(), customerSearchFormVo.getPageSize());
        if (userId == 1) {
            IPage<FrontUser> productOrderIPage = frontUserMapper.selectByConditionAdmin(page, customerSearchFormVo.getUserName());
            return new R<>(200, "查询成功", productOrderIPage);
        }
        IPage<FrontUser> productOrderIPage = frontUserMapper.selectByCondition(page, customerSearchFormVo.getUserName(), userId);
        return new R<>(200, "查询成功", productOrderIPage);
    }

    @Override
    public R<FrontUser> getCustomerByName(String userName) {
        QueryWrapper<FrontUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", userName);
        FrontUser frontUser = frontUserMapper.selectOne(queryWrapper);
        if (frontUser == null) {
            return new R<>(500, "用户不存在", null);
        }
        if (frontUser.getStatus().equals("1")) {
            return new R<>(500, "用户异常", null);
        }
        return new R<>(200, "查询成功", frontUser);

    }

    @Override
    public R<FrontUser> getUserInfo() {
        //获取Token
        String token = request.getHeader("token");
        // 获取用户名
        Object user = redisTemplate.opsForHash().get("user::login::" + token, "name");
        if (user == null) {
            return new R<>(401, "用户未登录", null);
        }
        QueryWrapper<FrontUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", user);
        FrontUser frontUser = frontUserMapper.selectOne(queryWrapper);
        return new R<>(200, "查询成功", frontUser);

    }
    @Override
    public R<FrontUser> updateInfo(FrontUser frontUser) {
        int i = frontUserMapper.updateById(frontUser);
        if (i > 0) {
            return new R<>(200, "修改成功", frontUser);
        } else {
            return new R<>(500, "修改失败", null);
        }
    }

    @Override
    public R<List<UserBalanceLog>> selectBalanceDetail(Integer userId) {
        List<UserBalanceLog> UserBalanceLog =userBalanceLogMapper.selectAllBalanceLog(userId);
        if (UserBalanceLog!=null){
            return new R<List<UserBalanceLog>>(200,"查询成功",UserBalanceLog);
        }
        return new R<List<UserBalanceLog>>(500,"查询失败",null);
    }


    @Override
    public R<List<UserIntegralLog>> selectCreditsDetail(Integer userId) {
        List<UserIntegralLog> userIntegralLog = userIntegralLogMapper.selectCreditsDetail(userId);
        if (userIntegralLog!=null){
            return new R<List<UserIntegralLog>>(200,"查询成功",userIntegralLog);
        }
        return new R<>(500,"查询失败",null);
    }

    @Override
    public R updateFrontUserStatus(FrontUser frontUser) {
        if (frontUser.getStatus().equals("1")){
            frontUser.setStatus("0");
        }else {
            frontUser.setStatus("1");
        }
        int i = frontUserMapper.updateById(frontUser);
        if (i>0){
            return new R(200,"修改成功",null);
        }
        return new R(500,"修改失败",null);
    }

    @Override
    @Transactional
    public R insertFrontUser(AddCarVo addCarVo) {

        Integer userId = addCarVo.getUserId();
        Integer storeId = addCarVo.getStoreId();

        // 添加到tb_front_user_store表
        FrontUserStore frontUserStore = new FrontUserStore();
        frontUserStore.setUserId(userId);
        frontUserStore.setStoreId(storeId);
        int insert = frontUserStoreMapper.insert(frontUserStore);

        // 添加到tb_user_balance表
        UserBalance userBalance = new UserBalance();
        userBalance.setUserId(userId);
        userBalance.setStoreId(storeId);
        userBalance.setAmount(new BigDecimal(0));
        // 设置时间为当前时间localDateTime
        userBalance.setBalanceTime(LocalDateTime.now());
        int insert1 = userBalanceMapper.insert(userBalance);

        // 添加到tb_user_integral表
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setStoreId(storeId);
        userIntegral.setCredits(0);
        userIntegral.setIntegralTime(LocalDateTime.now());
        int insert2 = userIntegralMapper.insert(userIntegral);

        if (insert > 0 && insert1 > 0 && insert2 > 0) {
            return new R(200, "添加成功", null);
        }
        return new R(500, "添加失败", null);

    }
}
